package com.sale.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sale.common.core.exception.GlobalException;
import com.sale.common.core.utils.StringUtils;
import com.sale.common.dict.utils.DictUtils;
import com.sale.common.mybatis.core.page.PageQuery;
import com.sale.common.mybatis.core.page.TableDataInfo;
import com.sale.common.satoken.utils.LoginHelper;
import com.sale.system.api.domain.SysDictData;
import com.sale.system.domain.*;
import com.sale.system.domain.dto.SysAuxiliaryDataDto;
import com.sale.system.domain.dto.SysTheDropDto;
import com.sale.system.domain.dto.UnitMessageDto;
import com.sale.system.domain.vo.SysAuxiliaryDataVo;
import com.sale.system.mapper.*;
import com.sale.system.service.ISysAuxiliaryDataService;
import com.sale.system.service.ISysDocumentService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author: YSL
 * @Date: 2023/7/13 10:31
 * @Desc: 辅助资料 业务层
 */
@RequiredArgsConstructor
@Service
public class SysAuxiliaryDataServiceImpl implements ISysAuxiliaryDataService {

    /**
     * 辅助资料Mapper
     */
    private final SysAuxiliaryDataMapper sysAuxiliaryDataMapper;

    /**
     * 辅助资料明细Mapper
     */
    private final SysAuxiliaryDetailMapper sysAuxiliaryDetailMapper;

    private final SysAuxiliaryUnitDetailMapper sysAuxiliaryUnitDetailMapper;

    @Resource
    ISysDocumentService sysDocumentService;


    private final MaterialAccessoriesMapper materialAccessoriesMapper;
    private final MaterialFinishedMapper materialFinishedMapper;
    private final MaterialHalfMapper materialHalfMapper;
    private final MaterialRawMapper materialRawMapper;
    private final MaterialWasteMapper materialWasteMapper;

    /**
     * 查询单计量单位列表
     *
     * @param sysAuxiliaryDataVo
     * @param pageQuery
     * @return
     */
    @Override
    public TableDataInfo<SysAuxiliaryData> selectPageAuxiliaryList(SysAuxiliaryDataVo sysAuxiliaryDataVo, PageQuery pageQuery) {

        // 模糊查询
        LambdaQueryWrapper<SysAuxiliaryData> lambdaQueryWrapper = new LambdaQueryWrapper<SysAuxiliaryData>()
            // 名称
            .like(StringUtils.isNotBlank(sysAuxiliaryDataVo.getAuxiliaryName()), SysAuxiliaryData::getAuxiliaryName, sysAuxiliaryDataVo.getAuxiliaryName())
            .eq(StringUtils.isNotBlank(String.valueOf(sysAuxiliaryDataVo.getAuxiliaryType())), SysAuxiliaryData::getAuxiliaryType, sysAuxiliaryDataVo.getAuxiliaryType());
        // 分页
        Page<SysAuxiliaryData> sysAuxiliaryDataPage = sysAuxiliaryDataMapper.selectPage(pageQuery.build(), lambdaQueryWrapper);
        return TableDataInfo.build(sysAuxiliaryDataPage);
    }

    /**
     * 查询单计量单位列表
     *
     * @param sysAuxiliaryDataVo
     * @param
     * @return
     */
    @Override
    public List<SysAuxiliaryData> listNotPage(SysAuxiliaryDataVo sysAuxiliaryDataVo) {

        // 模糊查询
        LambdaQueryWrapper<SysAuxiliaryData> lambdaQueryWrapper = new LambdaQueryWrapper<SysAuxiliaryData>()
            // 名称
            .eq(SysAuxiliaryData::getAuxiliaryType, 6);
        // 分页
        List<SysAuxiliaryData> sysAuxiliaryDataList = sysAuxiliaryDataMapper.selectList(lambdaQueryWrapper);
        return sysAuxiliaryDataList;
    }

    /**
     * 单个查询单计量单位
     *
     * @param auxiliaryId
     * @return
     */
    @Override
    public SysAuxiliaryData getSingleMeasurementUnitById(Long auxiliaryId) {
        return sysAuxiliaryDataMapper.selectById(auxiliaryId);
    }

    /**
     * 新增单计量单位
     *
     * @param sysAuxiliaryDataVo
     * @return
     */
    @Override
    public int insertSingleMeasurementUnit(SysAuxiliaryDataVo sysAuxiliaryDataVo) {
        SysAuxiliaryData sysAuxiliaryData = new SysAuxiliaryData();
        BeanUtils.copyProperties(sysAuxiliaryDataVo, sysAuxiliaryData);
        return sysAuxiliaryDataMapper.insert(sysAuxiliaryData);
    }

    /**
     * 修改单计量单位
     *
     * @param sysAuxiliaryDataVo
     * @return
     */
    @Override
    public int updateSingleMeasurementUnit(SysAuxiliaryDataVo sysAuxiliaryDataVo) {
        SysAuxiliaryData sysAuxiliaryData = new SysAuxiliaryData();
        BeanUtils.copyProperties(sysAuxiliaryDataVo, sysAuxiliaryData);
        return sysAuxiliaryDataMapper.updateById(sysAuxiliaryData);
    }

    /**
     * 删除单计量单位
     *
     * @param auxiliaryId
     * @return
     */
    @Override
    public int deleteSingleMeasurementUnit(Long auxiliaryId) {
        return sysAuxiliaryDataMapper.deleteById(auxiliaryId);
    }


    //************************************************* 辅助属性 *************************************************

    /**
     * 新增辅助属性
     *
     * @param sysAuxiliaryDataVo
     * @return
     */
    @Override
    public int insertAuxiliaryProperties(SysAuxiliaryDataVo sysAuxiliaryDataVo) {

        SysAuxiliaryData sysAuxiliaryData = new SysAuxiliaryData();
        BeanUtils.copyProperties(sysAuxiliaryDataVo, sysAuxiliaryData);
        sysAuxiliaryData.setModeCode(sysDocumentService.selectAuthorityCoding("informateManage:attribute:list"));
        sysAuxiliaryData.setCreateTime(new Date());
        sysAuxiliaryData.setCreateBy(LoginHelper.getUsername());
        sysAuxiliaryData.setMaterialCategory(Long.parseLong(sysAuxiliaryDataVo.getMaterialCategory()));
        // 新增辅助属性信息
        int insert = sysAuxiliaryDataMapper.insert(sysAuxiliaryData);
        if (insert > 0) {
            // 获取辅助属性明细信息,并新增
            List<SysAuxiliaryDetail> auxiliaryDetailList = sysAuxiliaryDataVo.getAuxiliaryDetailList();
            for (SysAuxiliaryDetail sysAuxiliaryDetail : auxiliaryDetailList) {
                sysAuxiliaryDetail.setAuxiliaryId(sysAuxiliaryData.getAuxiliaryId());
                sysAuxiliaryDetailMapper.insert(sysAuxiliaryDetail);
            }
        } else {
            throw new GlobalException("新增辅助属性失败");
        }
        return insert;
    }

    /**
     * 修改辅助属性
     *
     * @param sysAuxiliaryDataVo
     * @return
     */
    @Override
    public int updateAuxiliaryProperties(SysAuxiliaryDataVo sysAuxiliaryDataVo) {

        SysAuxiliaryData sysAuxiliaryData = new SysAuxiliaryData();
        BeanUtils.copyProperties(sysAuxiliaryDataVo, sysAuxiliaryData);
        sysAuxiliaryData.setMaterialCategory(Long.parseLong(sysAuxiliaryDataVo.getMaterialCategory()));
        // 修改辅助属性信息
        int update = sysAuxiliaryDataMapper.updateById(sysAuxiliaryData);
        if (update > 0) {
            // 删除辅助属性明细
            List<String> idList = new ArrayList<>();
            idList.add(String.valueOf(sysAuxiliaryData.getAuxiliaryId()));
            int delete = sysAuxiliaryDetailMapper.deleteByAuxiliaryDetailId(idList);
            if (delete > 0) {
                // 获取辅助属性明细信息,并新增
                List<SysAuxiliaryDetail> auxiliaryDetailList = sysAuxiliaryDataVo.getAuxiliaryDetailList();
                for (SysAuxiliaryDetail sysAuxiliaryDetail : auxiliaryDetailList) {
                    sysAuxiliaryDetail.setAuxiliaryId(sysAuxiliaryData.getAuxiliaryId());
                    sysAuxiliaryDetailMapper.insert(sysAuxiliaryDetail);
                }
            }
        } else {
            throw new GlobalException("修改辅助属性失败");
        }
        return update;
    }

    /**
     * 查询辅助属性列表
     *
     * @param sysAuxiliaryDataVo
     * @param pageQuery
     * @return
     */
    @Override
    public TableDataInfo<SysAuxiliaryDataDto> selectAuxiliaryPropertiesList(SysAuxiliaryDataVo sysAuxiliaryDataVo, PageQuery pageQuery) {
        //获取加工商状态缓存字典数据
        List<SysDictData> category = DictUtils.getDictCache("category_type");
        Map<String, String> categoryMap = category.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));


        // 查询辅助属性列表
        Page<SysAuxiliaryDataDto> sysAuxiliaryDataDtoPage = sysAuxiliaryDataMapper.selectAuxiliaryDataList(pageQuery.build(), sysAuxiliaryDataVo);

        List<SysAuxiliaryDataDto> records = sysAuxiliaryDataDtoPage.getRecords();
        for (SysAuxiliaryDataDto sysAuxiliaryDataDto : records) {
            // 获取辅助属性明细
            List<SysAuxiliaryDetail> auxiliaryDetail = sysAuxiliaryDetailMapper.getAuxiliaryDetail(sysAuxiliaryDataDto.getAuxiliaryId());
            sysAuxiliaryDataDto.setAuxiliaryDetailList(auxiliaryDetail);
            //物料类别
            sysAuxiliaryDataDto.setCategoryTypeName(categoryMap.get(String.valueOf(sysAuxiliaryDataDto.getCategoryType())));
        }

        return TableDataInfo.build(sysAuxiliaryDataDtoPage);
    }

    /**
     * 查询辅助属性列表(不分页)
     *
     * @param
     * @return
     */
    @Override
    public List<SysAuxiliaryDataDto> selectAuxiliaryDtoList(String categoryType) {

        // 查询辅助属性列表
        List<SysAuxiliaryDataDto> list = sysAuxiliaryDataMapper.selectAuxiliaryDtoList(categoryType);
        for (SysAuxiliaryDataDto sysAuxiliaryDataDto : list) {
            // 获取辅助属性明细
            List<SysAuxiliaryDetail> auxiliaryDetail = sysAuxiliaryDetailMapper.getAuxiliaryDetail(sysAuxiliaryDataDto.getAuxiliaryId());
            sysAuxiliaryDataDto.setAuxiliaryDetailList(auxiliaryDetail);
        }
        return list;
    }

    /**
     * 查询单个辅助属性
     *
     * @param auxiliaryId
     * @return
     */
    @Override
    public SysAuxiliaryDataDto getInfoAuxiliaryProperties(Long auxiliaryId) {
        // 查询辅助属性详情
        SysAuxiliaryDataDto auxiliaryDataDto = sysAuxiliaryDataMapper.getAuxiliaryData(auxiliaryId);
        // 查询辅助属性明细
        List<SysAuxiliaryDetail> auxiliaryDetail = sysAuxiliaryDetailMapper.getAuxiliaryDetail(auxiliaryDataDto.getAuxiliaryId());
        auxiliaryDataDto.setAuxiliaryDetailList(auxiliaryDetail);
        return auxiliaryDataDto;
    }

    /**
     * 删除辅助属性详情
     *
     * @param auxiliaryId
     * @return
     */
    @Override
    public int deleteAuxiliaryProperties(String auxiliaryId) {
        List<String> idList = Arrays.asList(auxiliaryId.split(","));
        // 删除辅助属性信息
        int deleteAuxiliary = sysAuxiliaryDataMapper.deleteBatchIds(idList);
        if (deleteAuxiliary > 0) {
            // 删除辅助属性明细
            sysAuxiliaryDetailMapper.deleteByAuxiliaryDetailId(idList);
        } else {
            throw new GlobalException("删除辅助属性失败");
        }
        return deleteAuxiliary;
    }

    /**
     * 单计量单位下拉
     *
     * @return
     */
    @Override
    public List<SysTheDropDto> selectUnitList() {
        return sysAuxiliaryDataMapper.selectUnitList();
    }

    /**
     * 根据单计量单位id查询详情
     *
     * @param auxiliaryId
     * @return
     */
    @Override
    public SysAuxiliaryData getByAuxiliaryData(Long auxiliaryId) {
        SysAuxiliaryData sysAuxiliaryData = sysAuxiliaryDataMapper.selectOne(new QueryWrapper<SysAuxiliaryData>()
            .lambda().eq(SysAuxiliaryData::getAuxiliaryId, auxiliaryId));
//            // 类型 1、单计量单位
//            .eq(SysAuxiliaryData::getAuxiliaryType, 1));
        return sysAuxiliaryData;
    }

    /**
     * 其他支出类别
     *
     * @return
     */
    @Override
    public List<SysTheDropDto> selectDisburseList() {
        return sysAuxiliaryDataMapper.selectDisburseList();
    }

    /**
     * 其他收入类别
     *
     * @return
     */
    @Override
    public List<SysTheDropDto> selectIncomeList() {
        return sysAuxiliaryDataMapper.selectIncomeList();
    }

    /**
     * 根据物料id获取单位相关信息（入库打印使用）
     */
    @Override
    public List<UnitMessageDto> getUnitMessage(String materialId) {
        List<UnitMessageDto> result = new ArrayList<>();
        //要找到是哪个物料的id
        MaterialAccessories materialAccessories = materialAccessoriesMapper.selectOne(new QueryWrapper<MaterialAccessories>()
            .lambda().eq(MaterialAccessories::getMaterialId, materialId));
        if (materialAccessories != null) {
            //获取基础单位
            UnitMessageDto unitMessageDto = new UnitMessageDto();
            SysAuxiliaryData sysAuxiliaryData = sysAuxiliaryDataMapper.selectOne(new QueryWrapper<SysAuxiliaryData>()
                .lambda().eq(SysAuxiliaryData::getAuxiliaryId, materialAccessories.getMaterialUnit()));
            unitMessageDto.setUnitId(sysAuxiliaryData.getAuxiliaryId());
            unitMessageDto.setUnitName(sysAuxiliaryData.getAuxiliaryName());
            unitMessageDto.setMinUnit(sysAuxiliaryData.getAuxiliaryName());
            unitMessageDto.setUnitContent("1");
            result.add(unitMessageDto);
            if (materialAccessories.getMaterialMoreUnit() != null) {
                //多单位数据
                List<SysAuxiliaryUnitDetail> sysAuxiliaryUnitDetails = sysAuxiliaryUnitDetailMapper.selectList(new QueryWrapper<SysAuxiliaryUnitDetail>()
                    .lambda().eq(SysAuxiliaryUnitDetail::getMaterialId, materialAccessories.getMaterialId()));
                for (SysAuxiliaryUnitDetail entity : sysAuxiliaryUnitDetails) {
                    UnitMessageDto unitMessageDto1 = new UnitMessageDto();
                    unitMessageDto1.setUnitId(entity.getAuxiliaryUnitId());
                    unitMessageDto1.setUnitName(entity.getUnitName());
                    unitMessageDto1.setMinUnit(sysAuxiliaryData.getAuxiliaryName());
                    unitMessageDto1.setUnitContent(entity.getUnitQuantity());
                    result.add(unitMessageDto1);
                }
            }
            return result;
        }

        MaterialFinished materialFinished = materialFinishedMapper.selectOne(new QueryWrapper<MaterialFinished>()
            .lambda().eq(MaterialFinished::getMaterialId, materialId));
        if (materialFinished != null) {
            //获取基础单位
            UnitMessageDto unitMessageDto = new UnitMessageDto();
            SysAuxiliaryData sysAuxiliaryData = sysAuxiliaryDataMapper.selectOne(new QueryWrapper<SysAuxiliaryData>()
                .lambda().eq(SysAuxiliaryData::getAuxiliaryId, materialFinished.getMaterialUnit()));
            unitMessageDto.setUnitId(sysAuxiliaryData.getAuxiliaryId());
            unitMessageDto.setUnitName(sysAuxiliaryData.getAuxiliaryName());
            unitMessageDto.setMinUnit(sysAuxiliaryData.getAuxiliaryName());
            unitMessageDto.setUnitContent("1");
            result.add(unitMessageDto);
            if (materialFinished.getMaterialMoreUnit() != null) {
                //多单位数据
                List<SysAuxiliaryUnitDetail> sysAuxiliaryUnitDetails = sysAuxiliaryUnitDetailMapper.selectList(new QueryWrapper<SysAuxiliaryUnitDetail>()
                    .lambda().eq(SysAuxiliaryUnitDetail::getMaterialId, materialFinished.getMaterialId()));
                for (SysAuxiliaryUnitDetail entity : sysAuxiliaryUnitDetails) {
                    UnitMessageDto unitMessageDto1 = new UnitMessageDto();
                    unitMessageDto1.setUnitId(entity.getAuxiliaryUnitId());
                    unitMessageDto1.setUnitName(entity.getUnitName());
                    unitMessageDto1.setMinUnit(sysAuxiliaryData.getAuxiliaryName());
                    unitMessageDto1.setUnitContent(entity.getUnitQuantity());
                    result.add(unitMessageDto1);
                }
            }
            return result;
        }
        MaterialHalf materialHalf = materialHalfMapper.selectOne(new QueryWrapper<MaterialHalf>()
            .lambda().eq(MaterialHalf::getMaterialId, materialId));
        if (materialHalf != null) {
            //获取基础单位
            UnitMessageDto unitMessageDto = new UnitMessageDto();
            SysAuxiliaryData sysAuxiliaryData = sysAuxiliaryDataMapper.selectOne(new QueryWrapper<SysAuxiliaryData>()
                .lambda().eq(SysAuxiliaryData::getAuxiliaryId, materialHalf.getMaterialUnit()));
            unitMessageDto.setUnitId(sysAuxiliaryData.getAuxiliaryId());
            unitMessageDto.setUnitName(sysAuxiliaryData.getAuxiliaryName());
            unitMessageDto.setMinUnit(sysAuxiliaryData.getAuxiliaryName());
            unitMessageDto.setUnitContent("1");
            result.add(unitMessageDto);
            if (materialHalf.getMaterialMoreUnit() != null) {
                //多单位数据
                List<SysAuxiliaryUnitDetail> sysAuxiliaryUnitDetails = sysAuxiliaryUnitDetailMapper.selectList(new QueryWrapper<SysAuxiliaryUnitDetail>()
                    .lambda().eq(SysAuxiliaryUnitDetail::getMaterialId, materialHalf.getMaterialId()));
                for (SysAuxiliaryUnitDetail entity : sysAuxiliaryUnitDetails) {
                    UnitMessageDto unitMessageDto1 = new UnitMessageDto();
                    unitMessageDto1.setUnitId(entity.getAuxiliaryUnitId());
                    unitMessageDto1.setUnitName(entity.getUnitName());
                    unitMessageDto1.setMinUnit(sysAuxiliaryData.getAuxiliaryName());
                    unitMessageDto1.setUnitContent(entity.getUnitQuantity());
                    result.add(unitMessageDto1);
                }
            }
            return result;
        }
        MaterialRaw materialRaw = materialRawMapper.selectOne(new QueryWrapper<MaterialRaw>()
            .lambda().eq(MaterialRaw::getMaterialId, materialId));
        if (materialRaw != null) {
            //获取基础单位
            UnitMessageDto unitMessageDto = new UnitMessageDto();
            SysAuxiliaryData sysAuxiliaryData = sysAuxiliaryDataMapper.selectOne(new QueryWrapper<SysAuxiliaryData>()
                .lambda().eq(SysAuxiliaryData::getAuxiliaryId, materialRaw.getMaterialUnit()));
            unitMessageDto.setUnitId(sysAuxiliaryData.getAuxiliaryId());
            unitMessageDto.setUnitName(sysAuxiliaryData.getAuxiliaryName());
            unitMessageDto.setMinUnit(sysAuxiliaryData.getAuxiliaryName());
            unitMessageDto.setUnitContent("1");
            result.add(unitMessageDto);
            if (materialRaw.getMaterialMoreUnit() != null) {
                //多单位数据
                List<SysAuxiliaryUnitDetail> sysAuxiliaryUnitDetails = sysAuxiliaryUnitDetailMapper.selectList(new QueryWrapper<SysAuxiliaryUnitDetail>()
                    .lambda().eq(SysAuxiliaryUnitDetail::getMaterialId, materialRaw.getMaterialId()));
                for (SysAuxiliaryUnitDetail entity : sysAuxiliaryUnitDetails) {
                    UnitMessageDto unitMessageDto1 = new UnitMessageDto();
                    unitMessageDto1.setUnitId(entity.getAuxiliaryUnitId());
                    unitMessageDto1.setUnitName(entity.getUnitName());
                    unitMessageDto1.setMinUnit(sysAuxiliaryData.getAuxiliaryName());
                    unitMessageDto1.setUnitContent(entity.getUnitQuantity());
                    result.add(unitMessageDto1);
                }
            }
            return result;
        }
        MaterialWaste materialWaste = materialWasteMapper.selectOne(new QueryWrapper<MaterialWaste>()
            .lambda().eq(MaterialWaste::getMaterialId, materialId));
        if (materialWaste != null) {
            //获取基础单位
            UnitMessageDto unitMessageDto = new UnitMessageDto();
            SysAuxiliaryData sysAuxiliaryData = sysAuxiliaryDataMapper.selectOne(new QueryWrapper<SysAuxiliaryData>()
                .lambda().eq(SysAuxiliaryData::getAuxiliaryId, materialWaste.getMaterialUnit()));
            unitMessageDto.setUnitId(sysAuxiliaryData.getAuxiliaryId());
            unitMessageDto.setUnitName(sysAuxiliaryData.getAuxiliaryName());
            unitMessageDto.setMinUnit(sysAuxiliaryData.getAuxiliaryName());
            unitMessageDto.setUnitContent("1");
            result.add(unitMessageDto);
            if (materialWaste.getMaterialMoreUnit() != null) {
                //多单位数据
                List<SysAuxiliaryUnitDetail> sysAuxiliaryUnitDetails = sysAuxiliaryUnitDetailMapper.selectList(new QueryWrapper<SysAuxiliaryUnitDetail>()
                    .lambda().eq(SysAuxiliaryUnitDetail::getMaterialId, materialWaste.getMaterialId()));
                for (SysAuxiliaryUnitDetail entity : sysAuxiliaryUnitDetails) {
                    UnitMessageDto unitMessageDto1 = new UnitMessageDto();
                    unitMessageDto1.setUnitId(entity.getAuxiliaryUnitId());
                    unitMessageDto1.setUnitName(entity.getUnitName());
                    unitMessageDto1.setMinUnit(sysAuxiliaryData.getAuxiliaryName());
                    unitMessageDto1.setUnitContent(entity.getUnitQuantity());
                    result.add(unitMessageDto1);
                }
            }
            return result;
        }
        return null;
    }


}
